import string

from django.contrib import auth
from django.contrib.auth import authenticate, login
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.utils import text
from django.views.decorators.csrf import csrf_exempt
# from django.contrib.auth.models import AbstractUser
import json

from rest_framework.views import APIView
from django.db.models import Q

from rest_framework import request

from items.models import items
from orders.models import orders


# Create your views here.
from django.core import serializers
from rest_framework.response import Response

from items.serializers import ItemsSerializers, ItemsPageNumberPagination
from orders.serializers import OrdersPageNumberPagination, OrdersSerializers
from users import models
from users.serializers import UserSerializer
from collections import OrderedDict

@csrf_exempt
def logInOut(request, user=None):

  if request.method == 'GET':
    #return HttpResponse("???")
    # req = json.loads(request.body)
    #
    data = request.GET
    # return HttpResponse(request.GET.get('password'))
    # data = json.loads(request.body.decode('utf-8'))
    reqtype = data.get('typecode')
    if reqtype == '1':
      #这块要改变一下登录状态
      request.session.flush()
      # del request.session['username']
      return JsonResponse({'code': 200, 'msg': '登出成功', 'data': ''})
    username = data.get('phoneNumber')
    password = data.get('password')
    newuser = auth.authenticate(username = username,password = password)
    # return HttpResponse(username)
    if newuser is None:
      return JsonResponse({'code': 101, 'msg': '用户名或密码错误', 'data': ''})

    login(request,newuser)
    request.session['username'] = username
    request.session.set_test_cookie()
    # user = authenticate(username = username, password = password)
    # newlist = models.user.objects.filter(username = username)
    # if len(newlist)== 0 :
    #   return JsonResponse({'code': 101, 'msg': '用户名或密码错误', 'data': ''})
    # newuser = models.user.objects.get(username = username)
    # if(password != newuser.password):
    #   return JsonResponse({'code': 101, 'msg': '用户名或密码错误', 'data': ''})
    #   改变登陆状态
    # request.session['isLogin'] = True


    return JsonResponse({'code': 200, 'msg': '登录成功', 'data': ''})
    # return JsonResponse({'code': 101, 'msg': '用户名或密码错误', 'data': ''})


  elif request.method == 'POST':
    req = json.loads(request.body.decode('utf-8'))
    if len(models.user.objects.filter(username = req['phoneNumber']) )== 0 :
      if len(req['phoneNumber']) != 11:
        return JsonResponse({'code': 101, 'msg': '输入手机号不正确', 'data': ''})
      elif len(models.user.objects.filter(username = req['phoneNumber'])):
        return JsonResponse({'code': 101, 'msg': '输入手机号已被注册', 'data': ''})
      elif len(req['stuID']) != 10:
        return JsonResponse({'code': 101, 'msg': '输入学号不正确', 'data': ''})
      elif len(models.user.objects.filter(stuID = req['stuID'])):
        return JsonResponse({'code': 101, 'msg': '输入学号已被注册', 'data': ''})
      elif len(req['password']) < 8 or len(req['password']) > 20:
        return JsonResponse({'code': 101, 'msg': '输入密码格式不正确', 'data': ''})
      elif len(req['nickname']) < 5 or len(req['nickname'] )> 20:
        return JsonResponse({'code': 101, 'msg': '输入昵称格式不正确', 'data': ''})
      elif req['password'] != req['password2']:
        return JsonResponse({'code': 101, 'msg': '两次输入密码不一致', 'data':''})
      elif len(models.user.objects.filter(nickname=req['nickname'])) > 0:
        return JsonResponse({'code': 101, 'msg': '昵称重复', 'data':''})
      if 'userPicture' in req:
        models.user.objects.create_user(username = req['phoneNumber'],password = req['password'],stuID = req['stuID'],nickname = req['nickname'],userPro = req['userPro'],userAns = req['userAns'],userPicture = req['userPicture'])
      else:
        models.user.objects.create_user(username = req['phoneNumber'],password = req['password'],stuID = req['stuID'],nickname = req['nickname'],userPro = req['userPro'],userAns = req['userAns'])

      #models.user.save()
      return JsonResponse({'code': 200, 'msg': '注册成功', 'data': ''})
      #return HttpResponse(len(models.user.objects.filter(username = req['phoneNumber']) ))
    else:
      #return HttpResponse(len(models.user.objects.filter(username=req['phoneNumber'])))
      return JsonResponse({'code': 101, 'msg': '用户名已存在', 'data': ''})
@csrf_exempt
def selfmsg(request):
    if request.method == 'GET':
      # data = request.GET
      # data = json.loads(request.body.decode('utf-8'))
      # username = data.get('phoneNumber')
      # # return HttpResponse(request.session['username'])
      # if ('username' in request.session) is False :
      #   return JsonResponse({'code': 101, 'msg': '该用户尚未登录！', 'data': ''})
      # if request.session['username'] != username :
      #
      #   return JsonResponse({'code': 101, 'msg': '该用户尚未登录！', 'data': ''})
      username = request.session['username']
      p = models.user.objects.all().values('username','nickname','stuID','date_joined')
      # # return HttpResponse(len(p))
      # p = p.filter(username = username)
      # # return HttpResponse(p)
      # # res = serializers.serialize('json',p)
      # res = {}
      # res['list'] = json.loads(serializers.serialize("json",p))
      # return JsonResponse(res)
      p = models.user.objects.all().filter(username = username)
      serializer = UserSerializer(instance=p,many=True)
      # return HttpResponse(username)
      data = serializer.data[0]
      response = {'code':200,'msg':'查看成功','data':data}
      return JsonResponse(response)

    if request.method == 'PUT':
      req = json.loads(request.body.decode('utf-8'))
      # if ('username' in request.session) is False:
      #   return JsonResponse({'code': 101, 'msg': '该用户尚未登录！', 'data': ''})
      # if request.session['username'] != req['phoneNumber']:
      #   return JsonResponse({'code': 101, 'msg': '该用户尚未登录！', 'data': ''})
      username = request.session['username']
      newuser = auth.authenticate(username = request.session['username'],password = req['password'])
      if newuser is None:

        return JsonResponse({'code': 101, 'msg': '输入密码错误', 'data': ''})
      if 'stuID' in req and req['stuID'] != "" :
        temp = models.user.objects.get(username = username)
        temp.stuID = req['stuID']
        temp.save()
      if 'newPhoneNumber' in req and req['newPhoneNumber'] != "" :
        temp = models.user.objects.get(username = username)
        temp.username = req['newPhoneNumber']
        request.session['username'] = temp.username
        temp.save()

      if 'nickname' in req and req['nickname'] != "":
        temp = models.user.objects.get(username = username)
        temp.nickname = req['nickname']
        temp.save()

      return JsonResponse({'code': 200, 'msg': '信息修改成功', 'data': ''})

    # if 'newPassword' in req and 'userAns' not in req:  # 前端判断在第一步
    #   temp = models.user.objects.get(username=req['phoneNumber'])
    #   return JsonResponse({'code': 200, 'msg': '回答密保问题', 'data': temp.userPro})
    # if 'userAns' in req:  # 前端判断出来是第二部
    #   temp = models.user.objects.get(username=req['phoneNumber'])
    #   if temp.userAns != req['userAns']:
    #     return JsonResponse({'code': 101, 'msg': '密保答案错误', 'data': ''})
    #   temp.set_password(req['newPassword'])
    #   temp.save()
    if request.method == 'POST':
      req = json.loads(request.body.decode('utf-8'))
      if req['typecode'] == 0 and 'newPassword' not in req:
        temp = models.user.objects.get(username=request.session['username'])
        userPro = temp.userPro
        return JsonResponse({'code': 200, 'msg': '返回密保问题', 'data': userPro})
      elif req['typecode'] == 0 and 'newPassword' in req:
        temp = models.user.objects.get(username=request.session['username'])
        if req['userAns'] != temp.userAns:
          return JsonResponse({'code': 101, 'msg': '密保问题错误', 'data': ''})
        elif req['newPassword'] != req['Password2']:
          return JsonResponse({'code': 101, 'msg': '两次输入密码不一致', 'data': ''})
        temp.set_password(req['newPassword'])
        temp.save()
        return JsonResponse({'code': 200, 'msg': '重置密码成功！请登录账号', 'data': ''})

      elif req['typecode'] == 1:
        temp = models.user.objects.get(username=request.session['username'])
        newuser = auth.authenticate(username=request.session['username'], password=req['password'])
        if newuser is None:
          return JsonResponse({'code': 101, 'msg': '旧密码错误', 'data': ''})
        elif req['password2'] != req['newPassword']:
          return JsonResponse({'code': 101, 'msg': '两次输入密码不一致', 'data': ''})
        temp.set_password(req['password2'])
        temp.save()
        request.session.flush()
        return JsonResponse({'code': 200, 'msg': '修改密码成功！请登录账号', 'data': ''})

@csrf_exempt
def msg(request,self):#查看其他人信息
  if request.method != 'GET':
    return JsonResponse({'code': 101, 'msg': '请求格式出错', 'data': ''})
  req = json.loads(request.body.decode('utf-8'))
  if req['phoneNumber'] == request.session['username']:
    return selfmsg(request)
  p = models.user.objects.all().values('username', 'nickname', 'stuID', 'date_joined')
  p = models.user.objects.all().filter(username=req['phoneNumber'])
  if len(p) == 0:
    return JsonResponse({'code': 101, 'msg': '该用户不存在', 'data': ''})
  serializer = UserSerializer(instance=p, many=True)
  # return HttpResponse(serializer)
  return HttpResponse(json.dumps(serializer.data[0]))


@csrf_exempt
def res(request,*args,**kwargs): #发布资源

  if 'username' not in request.session:
    return HttpResponse('非法！')
  if request.method == 'POST':


     data = json.loads(request.body)
     # data = request.body.decode('utf-8')
     if (data['itemsType']=='公共资源' or data['itemsType']=='个人资源' or data['itemsType']=='个人能力') == False:
       return JsonResponse({'code': 101, 'msg': '资源类型参数不合法', 'data': ''})
     if (len(data['itemsName'])) <= 0 or (len(data['itemsName'])) > 30:
       return JsonResponse({'code': 101, 'msg': '资源名称长度不合法', 'data': ''})
     if float(data['itemsPrice']) < 0 :
       return JsonResponse({'code': 101, 'msg': '资源单价不合法', 'data': ''})
     if int(data['itemsMaxNum']) <= 0:
       return JsonResponse({'code': 101, 'msg': '资源发布数量不合法', 'data': ''})
     if len(data['remark']) < 0 or len(data['remark']) > 50:
       return JsonResponse({'code': 101, 'msg': '资源备注长度不合法', 'data': ''})
     # seller = models.user.objects.get(username = request.session['username'])
     # data['itemsPublisher'] = seller.uuid
     # items = ItemsSerializers(data = data)
     # # publisher = models.user.objects.filter(username = request.session['username']).
     # # items['itemsPublisher'] = publisher
     # if items.is_valid() :
     #   # return HttpResponse(items['itemsPublisher_id'])
     #
     #   # return HttpResponse(items['remark'])
     #
     #   items.save()
     #
     #   return JsonResponse({'code': 200, 'msg': '发布成功', 'data': ''})
     # return JsonResponse({'code': 101, 'msg': '发布失败，请检查参数', 'data': ''})


     str_data = data['itemsStartTime']
     list_data = str_data.split(",")
     for var in list_data:
      newitems = items(itemsName=data['itemsName'], itemsPrice=data['itemsPrice'], itemsMaxNum=data['itemsMaxNum'],
                      remark=data['remark'])
      newitems.itemsPublisher = models.user.objects.get(username=request.session['username'])
      # newitems.itemsLastTime = data['itemsLastTime']
      newitems.itemsNumber = newitems.itemsMaxNum
      newitems.itemsType = data['itemsType']
      newitems.itemsStartTime = var
      if 'itemsPicture' in data :
        newitems.itemsPicture = data['itemsPicture']
      if 'itemsEndTime' not in data:
        data['itemsEndTime'] = ''
      if data['itemsEndTime'] == '':
        newitems.itemsEndTime = newitems.itemsStartTime
      else :
        newitems.itemsEndTime = data['itemsEndTime']
      newitems.save()
     return JsonResponse({'code': 200, 'msg': '发布成功', 'data': ''})

  elif request.method == 'GET':
       request = APIView().initialize_request(request)
       username = request.session['username']
       thisuser = models.user.objects.get(username = username)
       userItems = items.objects.filter(itemsPublisher = thisuser)
       if 'typecode' in request.GET:
         typecode = request.GET['typecode']
         if typecode == "已售罄":
           userItems = userItems.filter(itemsNumber=0)
         elif typecode == "上架中":
           userItems = userItems.exclude(itemsNumber=0)

       # return HttpResponse(request.GET.get('limit'))
       pg = ItemsPageNumberPagination()
       page_roles = pg.paginate_queryset(queryset=userItems,request=request,view=None)
       ser = ItemsSerializers(instance=page_roles,many=True)
       for i in range(len(ser.data)):
        ser.data[i]['itemsID'] = str(ser.data[i]['itemsID']).replace("-","")
       response = {'code':200,'msg':'获取成功并返回页面','count':1000000,'data':ser.data}
       return JsonResponse(response)
  # elif request.method == 'GET':
  #   data = request.GET
  #   # return HttpResponse(data)
  #   limit = data['limit']
  #   page = data['page']
  #   username = request.session.get('username')
  #   thisuser = models.user.objects.get(username=username)
  #   it = items.objects.filter(itemsPublisher=thisuser)
  #   num = len(it)
  #   totalpage = (num + limit - 1) / limit
  #   itlist = list(it)
  #   data = []
  #   data[0:min(limit - 1, totalpage - (page - 1) * limit) - 1] = it[(page - 1) * limit:min(limit * page - 1, num - 1)]
  #   res = {'code': 200, 'msg': '成功', 'data': data, 'totalpage': totalpage}
  #   return JsonResponse(res)



@csrf_exempt
def optItems(request,self,*args):# 删除或查看资源
  if 'username' not in request.session:
    return JsonResponse({'code': 101, 'msg': '用户未登录！', 'data': ''})
  if request.method == 'DELETE':
    data = json.loads(request.body.decode('utf-8'))
    itemsID = data['itemsID']
    olditem = items.objects.filter(itemsID=itemsID)
    if len(olditem) == 0:
      return JsonResponse({'code': 101, 'msg': '没有此物品', 'data': ''})
    olditem = items.objects.get(itemsID=itemsID)
    olditem.delete()
    return JsonResponse({'code': 200, 'msg': '删除成功', 'data': ''})

  if request.method == 'GET':
    data = json.loads(request.body.decode('utf-8'))
    itemsID = data['itemsID']
    thisitem = items.objects.all().filter(itemsID=itemsID)
    if len(thisitem) == 0:
      return JsonResponse({'code': 101, 'msg': '没有此物品', 'data': ''})
    # response = {}
    # response['code'] = 200
    # response['msg'] = '成功'
    # item = thisitem.values('itemsID', 'itemsName', 'itemsPrice', 'itemsStartTime', 'itemsLastTime', 'itemsNumber',
    #                        'itemsMaxNum', 'remark')
    # list_dict = item.values()
    # response['data'] = json.dumps(list_dict,ensure_ascii=False)
    # response = json.dumps(response)
    # return HttpResponse(response)
    thisitem = items.objects.all().filter(itemsID=itemsID)
    serializer = ItemsSerializers(instance=thisitem, many=True)
    resdata = serializer.data[0]
    res = {'code':200,'msg':'成功','data':resdata}
    return JsonResponse(res)

@csrf_exempt
def optOrders(request,self,*args):
  if 'username' not in request.session:
    return JsonResponse({'code': 101, 'msg': '用户未登录！', 'data': ''})
  if request.method == 'GET':
    req = request.GET
    orderID = req['orderID']
    data = {}
    order = orders.objects.filter(orderID = orderID)
    if len( order ) == 0 :
      return JsonResponse({'code': 101, 'msg': '没有此订单', 'data': ''})
    # order = orders.objects.get(orderID = orderID)
    thisorder= orders.objects.all().filter(orderID = orderID)
    serializer = OrdersSerializers(instance=thisorder, many=True)
    resdata = serializer.data[0]
    resdata['orderID'] = resdata['orderID'].replace("-", "")
    resdata['orderItemsID'] = resdata['orderItemsID'].replace("-", "")
    res = {'code': 200, 'msg': '成功', 'data': resdata}
    return JsonResponse(res)

  if request.method == 'PUT':
    data = json.loads(request.body.decode('utf-8'))
    opType = data['type']
    orderID = data['orderID']
    order = orders.objects.get(orderID = orderID)
    user = models.user.objects.get(username = request.session['username'])
    if order.orderStatus == '已取消' or order.orderStatus == '已完成':
      return JsonResponse({'code': 101, 'msg': '订单已结束！', 'data': ''})
    if order.orderStatus == '待审批' and user!= order.seller:
      return JsonResponse({'code': 101, 'msg': '权限不够', 'data': ''})
    if order.orderStatus == '待付款' and user!= order.buyer:
      return JsonResponse({'code': 101, 'msg': '权限不够', 'data': ''})
    if opType == '确认' or opType == '审批':
      order.orderStatus = '已完成'
    else :
      order.orderStatus = '已取消'
      item = items.objects.get(itemsID = order.orderItemsID)
      num = order.orderItemsNum
      item.itemsNumber += num
      item.save()
    order.save()
    return JsonResponse({'code':200, 'msg':'操作成功', 'data':''})

@csrf_exempt
def ord(request):#type 全部 未付款 未审批 待我审批
  if 'username' not in request.session:
    return JsonResponse({'code': 101, 'msg': '用户未登录！', 'data': ''})
  if request.method == 'GET':
    request = APIView().initialize_request(request)
    username = request.session['username']
    thisuser = models.user.objects.get(username = username)
    thisorder = orders.objects.all().filter(Q(buyer=thisuser)|Q(seller=thisuser))
    type = request.GET.get('type')
    if type == "3":
      thisorder = orders.objects.all().filter(seller = thisuser, orderStatus = '待审批')
    if type == "2":
      thisorder = orders.objects.all().filter(buyer=thisuser, orderStatus='待审批')
    if type == "1":
      thisorder = orders.objects.all().filter(buyer=thisuser, orderStatus='待付款')
    pg = OrdersPageNumberPagination()
    page_roles = pg.paginate_queryset(queryset=thisorder, request=request, view=None)
    ser = OrdersSerializers(instance=page_roles, many=True)
    for i in range(len(ser.data)):
      ser.data[i]['orderID'] = str(ser.data[i]['orderID']).replace("-","")
      ser.data[i]['orderItemsID'] = str(ser.data[i]['orderItemsID']).replace("-","")
    response = {'code': 200, 'msg': '获取成功并返回页面', 'count': 1000000, 'data': ser.data}
    return JsonResponse(response)